package com.tuo51.manager.controller;


import com.tuo51.childcare.domain.dailytask.DailyTaskTemplate;
import com.tuo51.childcare.domain.vo.DailyTaskTemplateVO;
import com.tuo51.childcare.repository.DailyTaskTemplateRepository;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.foudation.utils.CopyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 附近的合作伙伴
 */
@RestController
@RequestMapping("/mapi/dailytask")
@Api(value = "/mapi/dailytask", tags = "OP - 每日任务模板管理")
public class MAPIDailyTaskController {

    @Autowired
    DailyTaskTemplateRepository itemRepository;

    @Autowired
    MemVerificationCache cache;

    @RequestMapping(value = "/list", method = GET)
    @ApiOperation(value = "资源列表")
    public StatusResponse list(@RequestHeader(TICKET) String ticket,
                               @RequestParam(value = "pageNum", required = false, defaultValue = "0")Integer pageNum,
                               @RequestParam(value = "pageSize", required = false, defaultValue = "15")Integer pageSize,
                               @RequestParam(value = "month", required = false)Integer month,
                               @RequestParam(value = "orderBy", required = false)String orderBy,
                               @RequestParam(value = "searchBy", required = false) String searchBy){

        cache.getStaffId(ticket);

        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);

        Page<DailyTaskTemplateVO> ret = itemRepository.findAll(new Specification<DailyTaskTemplate>() {
            @Override
            public Predicate toPredicate(Root<DailyTaskTemplate> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                Predicate base = cb.isFalse(root.get("deleted"));

                if (StringUtils.isNotEmpty(searchBy)){
                    String key = "%" + searchBy + "%";
                    Predicate p = cb.or(cb.like(root.get("title"), key),
                            cb.like(root.get("description"), key),
                            cb.like(root.get("manual"), key));
                    base = cb.and(base, p);
                }

                if (month != null){
                    Predicate p1 = cb.lessThanOrEqualTo(root.get("monthMin"), month);
                    Predicate p2 = cb.greaterThan(root.get("monthMax"), month);
                    Predicate p = cb.and(p1, p2);
                    base = cb.and(base, p);
                }

                query.where(base);

                if (StringUtils.isNotEmpty(orderBy)){
                    query.orderBy(cb.asc(root.get(orderBy)));
                }else {
                    query.orderBy(cb.desc(root.get("created")));
                }

                return query.getRestriction();
            }
        }, pageRequest).map(k->DailyTaskTemplateVO.of(k));

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/info", method = GET)
    @ApiOperation(value = "内容详情")
    public StatusResponse info(@RequestHeader(TICKET) String ticket,
                                   String itemId){

        cache.getStaffId(ticket);

        return StatusResponse.success(itemRepository.getOne(itemId));
    }

    @RequestMapping(value = "/edit", method = POST)
    @ApiOperation(value = "编辑")
    public StatusResponse edit(@RequestHeader(TICKET) String ticket,
                               DailyTaskTemplateVO item){
        cache.getStaffId(ticket);


        DailyTaskTemplate ret = null;
        if (StringUtils.isNotEmpty(item.getId())){
            ret = itemRepository.getOne(item.getId());
        }else{
            ret = new DailyTaskTemplate();
        }

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "条目不存在");
        }

        CopyUtils.copyProperties(item, ret);

        itemRepository.save(ret);

        return StatusResponse.success(ret);
    }


    @RequestMapping(value = "/delete", method = POST)
    @ApiOperation("删除")
    public StatusResponse delete(@RequestHeader(TICKET) String ticket, String itemId) {

        String staffId = cache.getStaffId(ticket);


        DailyTaskTemplate ret = itemRepository.getOne(itemId);

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "条目不存在");
        }

        ret.setDeleted(true);

        itemRepository.save(ret);

        return StatusResponse.success();
    }
}
